from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI


def setup_cors(app: FastAPI):
    """
    配置CORS中间件以支持跨域请求
    """
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 开发环境允许所有源，生产环境应指定具体域名
        allow_credentials=True,
        allow_methods=["*"],  # 允许所有HTTP方法
        allow_headers=["*"],  # 允许所有请求头
        allow_origin_regex=None,
        expose_headers=[],    # 暴露给浏览器的响应头
        max_age=600,          # 预检请求缓存时间(秒)
    )


# 生产环境推荐配置
def setup_production_cors(app: FastAPI):
    """
    生产环境的CORS配置，更加严格和安全
    """
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[
            "https://yourdomain.com",
            "https://www.yourdomain.com",
            # 添加更多允许的域名
        ],
        allow_credentials=True,
        allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        allow_headers=[
            "Authorization",
            "Content-Type",
            "X-Requested-With",
            "Accept",
            "Origin",
            "Access-Control-Request-Method",
            "Access-Control-Request-Headers"
        ],
        expose_headers=["Content-Disposition"],
        max_age=86400,  # 24小时
    )